document.addEventListener('DOMContentLoaded', () => {
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    const startButton = document.getElementById('startButton');
    const scoreElement = document.getElementById('score');
    const levelElement = document.getElementById('level');

    // 设置画布大小
    canvas.width = 400;
    canvas.height = 400;

    // 游戏状态
    let gameState = {
        isRunning: false,
        score: 0,
        level: 1,
        rotationSpeed: 2,
        needles: [],
        currentNeedle: null,
        centerX: canvas.width / 2,
        centerY: canvas.height / 2,
        circleRadius: 100,
        needleLength: 80,
        rotation: 0,
        particles: [] // 用于存储特效粒子
    };

    // 粒子类（用于特效）
    class Particle {
        constructor(x, y) {
            this.x = x;
            this.y = y;
            this.vx = (Math.random() - 0.5) * 4;
            this.vy = (Math.random() - 0.5) * 4;
            this.alpha = 1;
            this.size = Math.random() * 3 + 1;
            this.color = `hsl(${Math.random() * 360}, 50%, 50%)`;
        }

        update() {
            this.x += this.vx;
            this.y += this.vy;
            this.alpha *= 0.95;
            this.size *= 0.95;
        }

        draw() {
            ctx.save();
            ctx.globalAlpha = this.alpha;
            ctx.fillStyle = this.color;
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
            ctx.fill();
            ctx.restore();
        }
    }

    // 针类
    class Needle {
        constructor(isStuck = false) {
            this.isStuck = isStuck;
            this.angle = 0;
            this.progress = 0;
            this.startY = gameState.centerY + 150;
            this.isMoving = false;
        }

        draw() {
            ctx.save();
            
            if (!this.isStuck) {
                // 绘制等待发射的针（固定在底部）
                const startX = gameState.centerX;
                const currentY = this.isMoving ? 
                    this.startY - (this.startY - (gameState.centerY + gameState.circleRadius)) * this.progress :
                    this.startY;
                
                ctx.translate(startX, currentY);
                
                ctx.beginPath();
                ctx.moveTo(0, 0);
                ctx.lineTo(0, gameState.needleLength);
                ctx.strokeStyle = '#2c3e50';
                ctx.lineWidth = 2;
                ctx.stroke();

                // 针头
                ctx.beginPath();
                ctx.arc(0, 0, 3, 0, Math.PI * 2);
                ctx.fillStyle = '#2c3e50';
                ctx.fill();
            } else {
                // 已插入的针（跟随圆盘旋转）
                ctx.translate(gameState.centerX, gameState.centerY);
                ctx.rotate(gameState.rotation + this.angle);
                
                ctx.beginPath();
                ctx.moveTo(0, gameState.circleRadius);
                ctx.lineTo(0, gameState.circleRadius + gameState.needleLength);
                ctx.strokeStyle = '#2c3e50';
                ctx.lineWidth = 2;
                ctx.stroke();

                // 针头
                ctx.beginPath();
                ctx.arc(0, gameState.circleRadius, 3, 0, Math.PI * 2);
                ctx.fillStyle = '#2c3e50';
                ctx.fill();
            }

            ctx.restore();
        }

        update() {
            if (!this.isStuck && this.isMoving && this.progress < 1) {
                this.progress += 0.15; // 增加移动速度
                // 如果针到达终点，立即插入
                if (this.progress >= 1) {
                    this.insert();
                }
            }
        }

        insert() {
            // 计算针的插入角度（相对于圆盘的角度）
            const insertAngle = -gameState.rotation;

            // 检查碰撞
            if (checkCollision(insertAngle)) {
                gameOver();
                return;
            }

            // 创建特效
            const hitX = gameState.centerX;
            const hitY = gameState.centerY + gameState.circleRadius;
            createParticles(hitX, hitY);

            // 处理针的插入
            this.isStuck = true;
            this.angle = insertAngle;
            gameState.needles.push(this);
            gameState.currentNeedle = new Needle(false);
            
            // 更新分数
            gameState.score++;
            scoreElement.textContent = gameState.score;

            // 升级逻辑
            if (gameState.score % 5 === 0) {
                gameState.level++;
                gameState.rotationSpeed += 0.5;
                levelElement.textContent = gameState.level;
            }
        }
    }

    // 创建特效
    function createParticles(x, y) {
        for (let i = 0; i < 20; i++) {
            gameState.particles.push(new Particle(x, y));
        }
    }

    // 初始化游戏
    function init() {
        // 设置画布大小
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        
        // 更新游戏状态
        gameState.centerX = canvas.width / 2;
        gameState.centerY = canvas.height / 2;
        gameState.circleRadius = Math.min(canvas.width, canvas.height) * 0.3;
        gameState.needleLength = gameState.circleRadius * 0.3;
        
        // 创建新的针
        gameState.currentNeedle = new Needle(false);
        
        // 添加触摸事件支持
        canvas.addEventListener('touchstart', (e) => {
            e.preventDefault(); // 防止触摸事件触发其他行为
            if (gameState.isRunning) {
                shootNeedle();
            } else {
                startGame();
            }
        });
        
        // 添加视口大小改变事件
        window.addEventListener('resize', () => {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
            gameState.centerX = canvas.width / 2;
            gameState.centerY = canvas.height / 2;
            gameState.circleRadius = Math.min(canvas.width, canvas.height) * 0.3;
            gameState.needleLength = gameState.circleRadius * 0.3;
        });
    }

    // 检查碰撞
    function checkCollision(newAngle) {
        for (let needle of gameState.needles) {
            const angleDiff = Math.abs(needle.angle - newAngle);
            // 转换到 0-180 度范围内
            const smallerAngle = angleDiff % Math.PI;
            const normalizedAngle = smallerAngle > Math.PI / 2 ? Math.PI - smallerAngle : smallerAngle;
            // 如果角度差小于5度（约0.087弧度），则认为发生碰撞
            if (normalizedAngle < 0.087) {
                return true;
            }
        }
        return false;
    }

    // 更新游戏
    function update() {
        // 更新圆盘旋转（无论游戏是否运行都转动）
        gameState.rotation += gameState.rotationSpeed * Math.PI / 180;

        // 更新当前针的动画
        if (gameState.currentNeedle) {
            gameState.currentNeedle.update();
        }

        // 更新粒子
        gameState.particles = gameState.particles.filter(particle => particle.alpha > 0.1);
        gameState.particles.forEach(particle => particle.update());

        draw();
        requestAnimationFrame(update);
    }

    // 绘制游戏
    function draw() {
        // 清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 绘制圆盘
        ctx.save();
        ctx.translate(gameState.centerX, gameState.centerY);
        ctx.rotate(gameState.rotation);
        
        // 绘制彩色圆盘
        const segments = 12;
        const angleStep = (Math.PI * 2) / segments;
        for (let i = 0; i < segments; i++) {
            ctx.beginPath();
            ctx.moveTo(0, 0);
            ctx.arc(0, 0, gameState.circleRadius, i * angleStep, (i + 1) * angleStep);
            ctx.fillStyle = `hsl(${(i * 360 / segments)}, 70%, 60%)`;
            ctx.fill();
        }

        // 添加圆心点
        ctx.beginPath();
        ctx.arc(0, 0, 5, 0, Math.PI * 2);
        ctx.fillStyle = '#2c3e50';
        ctx.fill();
        
        ctx.restore();

        // 绘制所有针
        for (let needle of gameState.needles) {
            needle.draw();
        }

        // 绘制当前针
        if (gameState.currentNeedle) {
            gameState.currentNeedle.draw();
        }

        // 绘制粒子特效
        gameState.particles.forEach(particle => particle.draw());

        // 如果游戏未开始，显示提示文字
        if (!gameState.isRunning) {
            ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = '#fff';
            ctx.font = '20px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('点击开始游戏', canvas.width / 2, canvas.height / 2);
        }
    }

    // 发射针
    function shootNeedle() {
        if (!gameState.isRunning || !gameState.currentNeedle || gameState.currentNeedle.isStuck) return;

        // 开始移动针
        gameState.currentNeedle.isMoving = true;
    }

    // 游戏结束
    function gameOver() {
        gameState.isRunning = false;
        startButton.textContent = '重新开始';
        alert(`游戏结束！\n得分：${gameState.score}\n关卡：${gameState.level}`);
    }

    // 事件监听
    startButton.addEventListener('click', () => {
        init();
        gameState.isRunning = true;
        startButton.textContent = '游戏中';
    });

    // 初始化游戏
    init();
    // 开始动画循环（让圆盘一直转动）
    update();
}); 